package cn.tedu.v6;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

/**
 * Version 6  在线用户列表 统计上线名称
 *            消息转发 --交互--服务器 客户端文字
 */
public class Server {
    private ServerSocket serverSocket;
    private static final Integer PORT = 9908;
    private List<PrintWriter> allOut=new ArrayList<>();
    //1.存储在线客户：onlineUsers
    private   Set<String> onlineUsers=new HashSet<>();
    private   Map<String,String> uerDatabase;//私有-

    public Server() {//公共+
        try {
            serverSocket = new ServerSocket(PORT);
            uerDatabase=new HashMap<>();
            uerDatabase.put("易易","121511");
            uerDatabase.put("想想","101211");

        } catch (BindException e) {
            System.out.println("请检查端口号，被占用");
        } catch (IOException e) {
            System.out.println("客户端没有链接上");
        }
    }


    public void start() {
        System.out.println("等待客户端连接");
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(new ClientHandler(socket)).start();
            }
        } catch (IOException e) {
            System.out.println("客户端链接断开链接");
        } finally {
            if (serverSocket != null && serverSocket.isClosed()) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败");
                }
                System.out.println("服务器关闭成功");
            }
        }
    }


    public static void main(String[] args) {
        new Server().start();
    }



    private class ClientHandler implements Runnable {
        private Socket socket;
        private String ip;
        private PrintWriter pw;
        private BufferedReader br;
        private String username;
        private String password;

        public ClientHandler(Socket s) {

            this.socket = s;
            ip = socket.getInetAddress().getHostAddress();
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
                pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);

            synchronized (allOut){
                allOut.add(pw);
            }

            } catch (IOException e) {
                System.out.println("客户端断开连接");
            }
           }
        private synchronized void broadcastMessage(String message){
            for(PrintWriter pw: allOut){
                pw.println("消息广播："+username+message);
            }
        }
        private synchronized void broadcastMessages(String message){
            for(PrintWriter pw: allOut){
                pw.println(message);
            }
        }
        //2.广播在线用户的列表方法  updateOnlineUsers  更新在线人数
        //提醒：没有参数、传入字符串保存所有的客户端名称
        //2.1 String userList="在线用户："+String.join("、",onlineUsers);
        //理解：拼接字符串，来客户名，记录一个客户端名
        //2.2来一个客户端，分发一个客户端消息：用户名消息
        private synchronized void updateOnlineUsers() {
            String userList = "在线用户：" + String.join("、", onlineUsers);
            broadcastMessages(userList);
        }

        private boolean Login(String user,String pass){
            return uerDatabase.containsKey(user)&&uerDatabase.get(user).equals(pass);
        }
        private void handleChat(){
            new Thread(() -> {
                try {
                    String message;
                    while ((message = br.readLine()) != null) {
                        System.out.println(username + "客户端：" + message);
                        System.out.print("服务器请输入：");
                        if (message.equalsIgnoreCase("exit")){
                            break;
                        }
                        broadcastMessage(message);

                    }
                } catch (IOException e) {
                    System.out.println(username+"断开连接~~~");
                }
            }).start();

            Scanner input = new Scanner(System.in);

            while (true) {
                System.out.println("服务器请输入：");
                String sme = input.nextLine();
                pw.println(sme);
                if (sme.equalsIgnoreCase("exit")){
                    pw.println(username+"我退出聊天室了~~~~~~~");
                    break;
                }

            }
        }
        public void run() {
            try {

                pw.println("请输入用户名");
                username=br.readLine();
                pw.println("请输入密码");
                password=br.readLine();

                if (Login(username,password)){
                    pw.println("登陆成功，欢迎进入晴天聊天室");
                    System.out.println(username+"客户端连接成功");

                    //3.判断客户端连接成功---加入集合中
                    //3.1【同步块：监视对象---集合】
                    // 3.2客户端登陆成功--名字加入集合中  方法？
                    //String username=br.readLine();
                    synchronized (onlineUsers) {
                        onlineUsers.add(username);
                        updateOnlineUsers();
                    }
                    handleChat();
                }else {
                    pw.println("登录失败，用户名或者密码错误");
                    socket.close();
                }

            } catch (IOException e){
                System.out.println("服务器端写出问题！！！");
            }
            finally {
                //4.同步块--从集合中一次移除用户名
                synchronized (onlineUsers){
                    onlineUsers.remove(username);
                }
                synchronized (allOut){
                    allOut.remove(pw);
                }


                if (pw != null)
                    pw.close();

                if (br != null)
                    try {
                        br.close();
                    } catch (IOException e) {
                        System.out.println("读入流断开连接");
                    }

                if (socket != null && !socket.isClosed()) {
                    System.out.println(username + "客户端退出服务器链接");
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println(ip + "客户端退出服务器链接");
                    }
                }
            }
        }
    }
}
